package com.travel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.travel.common.Result;
import com.travel.domain.entity.Address;
import com.travel.service.AddressService;
import com.travel.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    /**
     * 查询地址列表
     */
    @GetMapping("/list")
    public Result<List<Address>> list() {
        Long userId = BaseContext.getCurrentId();
        log.info("获取用户ID {} 的地址列表", userId);
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, userId);
        List<Address> addresses = addressService.list(wrapper);
        return Result.success(addresses);
    }

    /**
     * 根据ID查询地址详情
     */
    @GetMapping("/{id}")
    public Result<Address> getById(@PathVariable("id") Long id) {
        log.info("获取ID为 {} 的地址详情", id);
        Address address = addressService.getById(id);
        if (address == null) {
            return Result.error("地址不存在");
        }
        return Result.success(address);
    }

    /**
     * 添加新地址
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody Address address) {
        Long userId = BaseContext.getCurrentId();
        address.setUserId(userId);
        log.info("添加新地址: {}", address);
        boolean result = addressService.save(address);
        if (result) {
            return Result.success("地址添加成功");
        } else {
            return Result.error("地址添加失败");
        }
    }

    /**
     * 更新地址
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody Address address) {
        Long userId = BaseContext.getCurrentId();
        address.setUserId(userId);
        log.info("更新地址: {}", address);
        boolean result = addressService.updateById(address);
        if (result) {
            return Result.success("地址更新成功");
        } else {
            return Result.error("地址更新失败");
        }
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable("id") Long id) {
        log.info("删除ID为 {} 的地址", id);
        boolean result = addressService.removeById(id);
        if (result) {
            return Result.success("地址删除成功");
        } else {
            return Result.error("地址删除失败");
        }
    }
}
